<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Core_Controllers_Page extends Gio_Core_Controller
{
	public function layoutAction()
	{
		$request = $this->getRequest();
		
		$template = $request->getParam('template_id');
		$this->view->template = $template;
		
		$pageId = $request->getParam('page_id');
		$page = Modules_Core_Services_Page::getById($pageId);
		if (null == $page) {
			return;
		}
		
		$page['template_id'] = $template;
		$this->view->pageData = $page;
		
		$blocksData = array();
		$dataFile = TEMPLATE_DIR . DS . $template . DS . 'data' . DS . $page['route'] . '.xml';
		if (file_exists($dataFile)) {
			$blocksData = Modules_Core_Services_Page::importXml($dataFile);
		}
		$this->view->blocksData = $blocksData;
		
		if ($request->isPost()) {
			$this->setNoRender();
			$this->disableLayout();
			
			$blocks = $request->getPost('blocks');
			$newBlocks = array();
			if ($blocks) {
				foreach ($blocks as $index => $block) {
					if (isset($block['type']) && $block['type'] == 'widget') {
						$block['action'] = 'show';
					} else {
						$block['type'] = 'action';
					}
					$block['load'] = (isset($block['load']) && $block['load'] == 'ajax')
											? 'ajax' : 'php';
					$block['cache']['enable'] = (isset($block['cache']['enable']) && $block['cache']['enable'] == 'true')
													? 'true' : 'false';
					$block['cache']['timeout'] = (isset($block['cache']['timeout']) && $block['cache']['timeout'] > 0)
													? $block['cache']['timeout'] : 0;
					$newBlocks['block'][] = $block;
				}
			}
			
			$content = utf8_decode(Gio_Core_Array::toXml($newBlocks, 'pages'));
			
			Gio_Core_File::writeToFile($dataFile, $content);
			
			$this->getResponse()->setBody('RESULT_OK');
			return;
		}
		
		$layoutFile = TEMPLATE_DIR . DS . $template . DS . 'layouts' . DS . $page['route'] . '.phtml';
		if (!file_exists($layoutFile)) {
			return;
		}
		$blocks = Modules_Core_Services_Page::import($layoutFile);
		$this->view->blocks = $blocks;
	}
	
	public function listAction()
	{
		$request = $this->getRequest();
		
		$template = $request->getParam('template_id');
		$this->view->template = $template;
		
		$perPage = 20;
		$pageIndex = (int)$request->getParam('page_index');
		if (null == $pageIndex || '' == $pageIndex || $pageIndex < 0) {
			$pageIndex = 1;
		}
		$start = ($pageIndex - 1) * $perPage;
		$this->view->pageIndex = $pageIndex;
		
		$pages = Modules_Core_Services_Page::find(array(), $start, $perPage);
		$numPages = Modules_Core_Services_Page::count(array());
		
		$this->view->pages = $pages; 
		
		// Pager
		require_once LIB_DIR . DS . 'PEAR' . DS . 'Pager' . DS . 'Sliding.php';
		$pagerPath = $this->view->url('core_page_list', array('template_id' => $template));
		$pagerOptions = array(
			'mode'       	=> 'Sliding',
			'append'   		=> false,
    		'perPage'    	=> $perPage,
    		'delta'      	=> 5,
			'urlVar'		=> 'page',
			'path'			=> $pagerPath,
			'fileName'		=> 'page-%d',
			'separator'		=> '',
			'nextImg' 		=> '<small class="icon arrow_right"></small>',
			'prevImg'		=> '<small class="icon arrow_left"></small>',
			'altNext'		=> '',
			'altPrev'		=> '',
			'altPage'		=> '',
    		'totalItems' 	=> $numPages,
			'currentPage'	=> $pageIndex,
			'urlSeparator'	=> '/',
			'spacesBeforeSeparator' => 0,
			'spacesAfterSeparator' => 0,
			'curPageSpanPre' => '<a href="javascript: void();" class="current">',
			'curPageSpanPost' => '</a>'
		
		);
		$pager = new Pager_Sliding($pagerOptions);
		$this->view->pager = $pager;
	}
	
	public function addAction()
	{
		$request = $this->getRequest();
		
		$template = $request->getParam('template_id');
		$this->view->template = $template;
		
		$dbRoutesPage = Modules_Core_Services_Page::dbPages('route');
		$routes = array();
		if ($dbRoutesPage) {
			foreach ($dbRoutesPage as $index => $route) {
				$routes[] = $route['route'];
			}
		}
		
		$this->view->dbRoutesPage = $routes;
		
		$routesFrontend = Gio_Core_Route::getInstance()->getRoutes(true);
		$this->view->routesFrontend = $routesFrontend;
		
		if ($request->isPost()) {
			$pageData = $request->getPost('page');
			$pageData = Modules_Core_Services_Page::validate($pageData);
			
			if (isset($pageData['messages_error']) && $pageData['messages_error']) {
				$this->view->errorMessages = $pageData['messages'];
				$this->view->pageData = $pageData;
				return;
			}
			
			if (in_array($pageData['route'], $routes)) {
				Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('page_actions_add_exist'));
				$this->redirect($this->view->url('core_page_add', array('template_id' => $template)));
				return;
			}
			
			$page = array(
					'name' 	   	   => $pageData['name'],
					'description'  => $pageData['description'],
					'route'		   => $pageData['route'],					
					'created_date' => date('Y-m-d H:i:s'),
			);
			$pageId = Modules_Core_Services_Page::add($page);
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('page_actions_add_success'));
			$this->redirect($this->view->url('core_page_add', array('template_id' => $template)));
		}
	}
	
	public function contentAction()
	{
		$request = $this->getRequest();
				
		$template = $request->getParam('template_id');
		$this->view->template = $template;
		
		$pageId = $request->getParam('page_id');
		$page = Modules_Core_Services_Page::getById($pageId);
		if (null == $page) {
			return;
		}
		
		$page['template_id'] = $template;
		$this->view->page = $page;
		
		$templateFile = TEMPLATE_DIR . DS . $template . DS . 'layouts' . DS . $page['route'] . '.phtml';
		if (!file_exists($templateFile)) {
			throw new Exception('');
		}

		if ($request->isPost()) {
			$this->setNoRender();
			$this->disableLayout();
			
			$content = $request->getPost('content');
			Gio_Core_File::writeToFile($templateFile, $content);
			$this->getResponse()->setBody('RESULT_OK');
			return;
		}
		
		$content = file_get_contents($templateFile);
		$this->view->content = $content;
	}
	
	public function editAction()
	{
		$request = $this->getRequest();
		
		$template = $request->getParam('template_id');
		$this->view->template = $template;
		
		$pageId = $request->getParam('page_id');
		$page = Modules_Core_Services_Page::getById($pageId);
		if (null == $page) {
			return;
		}
		
		$page['template_id'] = $template;
		$this->view->pageData = $page;
		
		$dbRoutesPage = Modules_Core_Services_Page::dbPages('route');
		$routes = array();
		if ($dbRoutesPage) {
			foreach ($dbRoutesPage as $index => $route) {
				$routes[] = $route['route'];
			}
		}
		$this->view->dbRoutesPage = $routes;
		
		$routesFrontend = Gio_Core_Route::getInstance()->getRoutes(true);
		$this->view->routesFrontend = $routesFrontend;
		
		if ($request->isPost()) {
			$pageData = $request->getPost('page');
			$pageData = Modules_Core_Services_Page::validate($pageData);
			
			if (isset($pageData['messages_error']) && $pageData['messages_error']) {
				$this->view->errorMessages = $pageData['messages'];
				$pageData['page_id'] = $pageId;
				$pageData['template_id'] = $template;
				$this->view->pageData = $pageData;
				return;
			}
			
			if (in_array($pageData['route'], $routes) && $page['route'] != $pageData['route']) {
				Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('page_actions_edit_exist'));
				$this->redirect($this->view->url('core_page_edit', $page));
				return;
			}
			
			Modules_Core_Services_Page::update($pageData);
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('page_actions_edit_success'));
			$this->redirect($this->view->url('core_page_edit', $page));
		}
	}
	
	public function deleteAction()
	{
		$this->disableLayout();
		$this->setNoRender();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			$this->getResponse()->setBody('RESULT_NOT_OK');
		}
		
		$pageId = $request->getPost('page_id');
		Modules_Core_Services_Page::delete($pageId);
		$this->getResponse()->setBody('RESULT_OK');
	}
}